/*
 Copyright (c) 2008 TPSi
 Alex Iskander
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 */

#include "GenericConverter.h"
#include "../Bound.h"
#include <sstream>
#include <iomanip>

using namespace Bind;

std::string GenericConverter::doConversion(Bindable *property)
{
	/*
	 First, test if it is a string, as then we have to do almost nothing.
	 */
	//dynamic cast to string
	Bound<std::string> *stringVal = dynamic_cast<Bound<std::string> *> (property);
	
	//if we have it, use it.
	if (stringVal) return stringVal->get();
	
	/*
	 Next, test if it is an integer.
	 */
	//dynamic cast to integer
	Bound<int> *intVal = dynamic_cast<Bound<int> *> (property);
	
	//if it is an integer
	if (intVal)
	{
		/**
		 \todo Implement a more efficient number-conversion methodology here.
		 */
		//prepare a buffer
		std::ostringstream buffer;
				
		//print to the buffer
		buffer << intVal->get();
		
		//return the buffer
		return buffer.str();
	}
	
	/*
	 Next, test if it is a double.
	 */
	//dynamic cast to double
	Bound<double> *doubleVal = dynamic_cast<Bound<double> *> (property);
	
	//if it is a double
	if (doubleVal)
	{
		//prepare a buffer
		std::ostringstream buffer;
		
		//print to the buffer
		buffer << std::setprecision(3) << std::fixed << doubleVal->get();
		
		//return the buffer
		return buffer.str();
	}
	
	/*
	 Finally, test if it is a boolean.
	 */
	//dynamic cast to double
	Bound<bool> *boolValue = dynamic_cast<Bound<bool> *> (property);
	
	//if it is a double
	if (boolValue)
	{
		//return either "true" or "false"
		return (boolValue->get()) ? "true" : "false";
	}
	
	//failure, so return "(undefined)"
	return "(undefined)";
}